package com.example.electricbicycle.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.example.electricbicycle.po.User;
import com.example.electricbicycle.service.UserService;
import com.example.electricbicycle.service.UserServiceImpl;

@WebServlet("/UpdateUserServlet")
public class UpdateUserServlet extends HttpServlet {
    private final UserService userService = new UserServiceImpl();

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();

        // 清除所有旧消息
        session.removeAttribute("successMsg");
        session.removeAttribute("errorMsg");

        try {
            // 1. 获取当前登录用户
            User currentUser = (User) session.getAttribute("currentUser");

            // 权限验证 - 只有管理员可以编辑用户
            if (currentUser == null || currentUser.getRole() != 4) {
                session.setAttribute("errorMsg", "权限不足，只有管理员可以编辑用户");
                response.sendRedirect(request.getContextPath() + "/UserListServlet");
                return;
            }

            // 2. 获取要编辑的用户ID
            String uidParam = request.getParameter("id");
            if (uidParam == null || uidParam.trim().isEmpty()) {
                session.setAttribute("errorMsg", "无效的用户ID");
                response.sendRedirect(request.getContextPath() + "/UserListServlet");
                return;
            }

            int uid = Integer.parseInt(uidParam);

            // 3. 获取用户信息
            User user = userService.getUserById(uid);

            if (user != null) {
                request.setAttribute("user", user);
                request.getRequestDispatcher("/admin/updateuser.jsp").forward(request, response);
            } else {
                session.setAttribute("errorMsg", "用户不存在");
                response.sendRedirect(request.getContextPath() + "/UserListServlet");
            }

        } catch (NumberFormatException e) {
            session.setAttribute("errorMsg", "无效的用户ID格式");
            response.sendRedirect(request.getContextPath() + "/UserListServlet");
        } catch (Exception e) {
            session.setAttribute("errorMsg", "系统错误: " + e.getMessage());
            response.sendRedirect(request.getContextPath() + "/UserListServlet");
            e.printStackTrace();
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();

        // 清除所有旧消息
        session.removeAttribute("successMsg");
        session.removeAttribute("errorMsg");

        try {
            // 1. 获取当前登录用户
            User currentUser = (User) session.getAttribute("currentUser");

            // 权限验证
            if (currentUser == null || currentUser.getRole() != 4) {
                session.setAttribute("errorMsg", "权限不足，只有管理员可以更新用户");
                response.sendRedirect(request.getContextPath() + "/UserListServlet");
                return;
            }

            // 2. 获取用户ID
            int userId = Integer.parseInt(request.getParameter("id"));

            // 3. 创建用户对象
            User user = new User();
            user.setId(userId);
            user.setName(request.getParameter("name"));
            user.setPassword(request.getParameter("pass"));
            user.setRole(Integer.parseInt(request.getParameter("role")));

            // 4. 更新用户
            boolean isUpdated = userService.updateUser(user);

            // 5. 处理结果
            if (isUpdated) {
                session.setAttribute("successMsg", "用户信息更新成功");
            } else {
                session.setAttribute("errorMsg", "用户信息更新失败");
            }

        } catch (Exception e) {
            session.setAttribute("errorMsg", "系统错误: " + e.getMessage());
            e.printStackTrace();
        }

        response.sendRedirect(request.getContextPath() + "/UserListServlet");
    }
}